#pragma warning(disable:4005)
#include <drogon/HttpController.h>
#include "OCMain/ZipUtil.h"
#include "MyCap.h"
#include "doc.h"

using namespace drogon;
using namespace OCPP;

inline void setGZIp(HttpResponsePtr& resp)
{
	resp->addHeader("Content-Encoding", "gzip");
}

class CAPService : public HttpController<CAPService>
{
public:
	METHOD_LIST_BEGIN
		METHOD_ADD(CAPService::home, "", Get);
		METHOD_ADD(MyDoc::doc, "/doc?query={}", Get);
		METHOD_ADD(CAPService::getTimeList, "/getTimeList?startTime={startTime}&endTime={endTime}", Get);
		METHOD_ADD(CAPService::get, "/get?time={time}&product={product}", Get);
		METHOD_ADD(CAPService::cap3, "/getCAP3D?time={time}&z={z}&startX={x0}&startY={y0}&endX={x1}&endY={y1}", Get);
	METHOD_LIST_END
protected:
	void home(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback)
	{
		auto resp = drogon::HttpResponse::newHttpResponse();
		resp->setBody(String("<p>CAPService</p>"));
		callback(resp);
	}
	void getTimeList(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String startTime,String endTime)
	{
		auto resp = HttpResponse::newHttpResponse();
		auto timeVec = Singleton(MyCap).query(startTime,endTime);
		
		if (timeVec.empty())
		{
			resp->setBody("[]");
		}
		else
		{
			Json::Value value;
			for (const auto& time : timeVec)
			{
				value.append(time);
			}
			resp->setBody(value.toStyledString());
		}

		callback(resp);
	}

	void get(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String time,String product)
	{
		auto resp = HttpResponse::newHttpResponse();
		String gzContent = Singleton(MyCap).get(time, product);
		size_t size = gzContent.size();
		if (size != 0)
		{
			resp = drogon::HttpResponse::newFileResponse((const unsigned char*)gzContent.data(), size, "",
				CT_APPLICATION_OCTET_STREAM);
			setGZIp(resp);
		}
		else {
			resp->setStatusCode(HttpStatusCode::k404NotFound);
		}

		callback(resp);
	}

	
	void cap3(const HttpRequestPtr& req,
		std::function<void(const HttpResponsePtr&)>&& callback,
		String time,
		int z, int x0, int y0, int x1,int y1)
	{
		auto resp = HttpResponse::newHttpResponse();
		String gzContent = Singleton(MyCap).getCAP(time, z, x0, y0, x1, y1);
		size_t size = gzContent.size();
		if (size != 0)
		{
			String name = str_format("%d_%d_%d_%d_%d.bin", z, x0, y0, x1, y1);
			resp = drogon::HttpResponse::newFileResponse((const unsigned char*)gzContent.data(), gzContent.size(), name,
				CT_APPLICATION_OCTET_STREAM);
			setGZIp(resp);
		}
		else {
			resp->setStatusCode(HttpStatusCode::k404NotFound);
		}

		callback(resp);
	}
};